package com.zjd.association.controller;

import com.zjd.association.common.R;
import com.zjd.association.entity.ActiveLogs;
import com.zjd.association.entity.Users;
import com.zjd.association.handle.CacheHandle;
import com.zjd.association.service.ActiveLogsService;
import com.zjd.association.service.UsersService;
import com.zjd.association.utils.DateUtils;
import com.zjd.association.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


/**
 * 报名记录 控制层
 *
 * @author: zjd
 * @date: 2024-5-22
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/activeLogs")
public class ActiveLogsController {

    private final CacheHandle cacheHandle;

    private final UsersService usersService;

    private final ActiveLogsService activeLogsService;

    /**
     * 获取报名记录路径
     *
     * @return 报名记录路径
     */
    @RequestMapping("")
    public String index() {
        return "pages/ActiveLogs";
    }

    /**
     * 获取报名记录信息
     *
     * @param id 报名记录id
     * @return 报名记录
     */
    @GetMapping("/info")
    public R getInfo(String id) {
        ActiveLogs activeLogs = activeLogsService.getOne(id);
        return R.ok(activeLogs);
    }

    /**
     * 获取报名记录信息 列表
     *
     * @param activeId 活动id
     * @return 报名记录 列表
     */
    @GetMapping("/list")
    public R getList(String activeId) {
        List<Map<String, Object>> list = activeLogsService.getListByActiveId(activeId);
        return R.ok(list);
    }

    /**
     * 添加活动记录
     *
     * @param token      用户token
     * @param activeLogs 活动信息
     * @return 结果
     */
    @PostMapping("/add")
    public R addInfo(String token, ActiveLogs activeLogs) {
        //获取用户信息
        Users user = usersService.getOne(cacheHandle.getUserInfoCache(token));

        //判断用户是否参加了活动
        if (activeLogsService.isActive(activeLogs.getActiveId(), user.getId())) {
            activeLogs.setId(UUIDUtils.makeIDByCurrent());
            activeLogs.setUserId(user.getId());
            activeLogs.setCreateTime(DateUtils.getNowDate());

            //添加用户活动
            activeLogsService.add(activeLogs);
            return R.ok();
        } else {
            return R.warn("该活动您已参与，请勿重复报名");
        }
    }

    /**
     * 更新活动记录
     *
     * @param activeLogs 活动信息
     * @return 结果
     */
    @PostMapping("/upd")
    public R updInfo(ActiveLogs activeLogs) {
        activeLogsService.update(activeLogs);
        return R.ok();
    }

    /**
     * 删除活动记录
     *
     * @param id 活动记录id
     * @return 结果
     */
    @PostMapping("/del")
    public R delInfo(String id) {
        ActiveLogs activeLogs = activeLogsService.getOne(id);
        activeLogsService.delete(activeLogs);
        return R.ok();
    }
}